<template>
  <div class="logs-view">
    <el-card class="logs-card">
      <template #header>
        <div class="logs-header">
          <div class="section-title">📝 系统日志</div>
          <div class="logs-controls">
            <el-select v-model="logLevel" placeholder="日志级别" style="width: 120px">
              <el-option label="全部级别" value="all" />
              <el-option label="INFO" value="info" />
              <el-option label="WARN" value="warn" />
              <el-option label="ERROR" value="error" />
            </el-select>
            <el-select v-model="timeRange" placeholder="时间范围" style="width: 120px">
              <el-option label="今天" value="today" />
              <el-option label="最近3天" value="3days" />
              <el-option label="最近7天" value="7days" />
            </el-select>
            <el-input
              v-model="searchKeyword"
              placeholder="搜索日志内容..."
              style="width: 200px"
              clearable
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button @click="searchLogs">🔍 搜索</el-button>
            <el-button @click="clearLogs">🗑️ 清空</el-button>
          </div>
        </div>
      </template>
      
      <div class="log-container" ref="logContainer">
        <div
          v-for="(log, index) in filteredLogs"
          :key="index"
          class="log-entry"
          :class="log.level"
        >
          <span class="log-time">{{ log.time }}</span>
          <span class="log-level" :class="log.level">{{ log.level.toUpperCase() }}</span>
          <span class="log-message">{{ log.message }}</span>
        </div>
        
        <div v-if="filteredLogs.length === 0" class="no-logs">
          暂无日志记录
        </div>
      </div>
      
      <div class="log-footer">
        <div class="log-stats">
          总计: {{ logs.length }} 条 | 
          INFO: {{ infoCount }} 条 | 
          WARN: {{ warnCount }} 条 | 
          ERROR: {{ errorCount }} 条
        </div>
        <div class="log-actions">
          <el-button size="small" @click="exportLogs">📋 导出日志</el-button>
          <el-button size="small" @click="scrollToBottom">⬇️ 滚动到底部</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { Search } from '@element-plus/icons-vue'
import { useAppStore } from '@/stores/app'

const appStore = useAppStore()
const logs = computed(() => appStore.logs)

const logLevel = ref('all')
const timeRange = ref('today')
const searchKeyword = ref('')
const logContainer = ref<HTMLElement>()

// 过滤日志
const filteredLogs = computed(() => {
  let filtered = logs.value

  // 按级别过滤
  if (logLevel.value !== 'all') {
    filtered = filtered.filter(log => log.level === logLevel.value)
  }

  // 按关键词过滤
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(log => 
      log.message.toLowerCase().includes(keyword)
    )
  }

  return filtered
})

// 统计各级别日志数量
const infoCount = computed(() => logs.value.filter(log => log.level === 'info').length)
const warnCount = computed(() => logs.value.filter(log => log.level === 'warn').length)
const errorCount = computed(() => logs.value.filter(log => log.level === 'error').length)

const searchLogs = () => {
  ElMessage.success('搜索完成')
}

const clearLogs = () => {
  ElMessageBox.confirm('确定要清空所有日志吗？', '确认清空', {
    type: 'warning',
  }).then(() => {
    appStore.clearLogs()
    ElMessage.success('日志已清空')
  })
}

const exportLogs = () => {
  const logText = filteredLogs.value
    .map(log => `[${log.time}] ${log.level.toUpperCase()}: ${log.message}`)
    .join('\n')
  
  const blob = new Blob([logText], { type: 'text/plain' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `mediacrawler-logs-${new Date().toISOString().slice(0, 10)}.txt`
  a.click()
  URL.revokeObjectURL(url)
  
  ElMessage.success('日志已导出')
}

const scrollToBottom = () => {
  if (logContainer.value) {
    logContainer.value.scrollTop = logContainer.value.scrollHeight
  }
}

// 自动滚动到底部（当有新日志时）
watch(logs, () => {
  nextTick(() => {
    scrollToBottom()
  })
})

// 模拟添加日志
onMounted(() => {
  const timer = setInterval(() => {
    const messages = [
      '正在处理数据...',
      '网络请求成功',
      '数据解析完成',
      '保存到数据库',
      '任务进度更新',
    ]
    const levels: Array<'info' | 'warn' | 'error'> = ['info', 'info', 'info', 'warn', 'error']
    const randomMessage = messages[Math.floor(Math.random() * messages.length)]
    const randomLevel = levels[Math.floor(Math.random() * levels.length)]
    
    if (Math.random() > 0.7) { // 30% 概率添加新日志
      appStore.addLog(randomLevel, randomMessage)
    }
  }, 3000)

  onUnmounted(() => {
    clearInterval(timer)
  })
})
</script>

<style scoped>
.logs-view {
  max-width: 1200px;
  margin: 0 auto;
}

.logs-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.logs-controls {
  display: flex;
  gap: 10px;
  align-items: center;
  flex-wrap: wrap;
}

.log-container {
  background: #1e1e1e;
  color: #d4d4d4;
  border-radius: 8px;
  padding: 20px;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 13px;
  line-height: 1.5;
  max-height: 500px;
  overflow-y: auto;
  margin-bottom: 15px;
}

.log-entry {
  margin-bottom: 5px;
  display: flex;
  gap: 10px;
  padding: 2px 0;
}

.log-entry:hover {
  background: rgba(255, 255, 255, 0.05);
}

.log-time {
  color: #569cd6;
  min-width: 80px;
  font-weight: 500;
}

.log-level {
  min-width: 50px;
  font-weight: bold;
  text-align: center;
}

.log-level.info { color: #4ec9b0; }
.log-level.warn { color: #dcdcaa; }
.log-level.error { color: #f44747; }

.log-message {
  flex: 1;
  word-break: break-word;
}

.no-logs {
  text-align: center;
  color: #909399;
  padding: 40px;
  font-style: italic;
}

.log-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 15px;
  border-top: 1px solid #e4e7ed;
  font-size: 12px;
  color: #909399;
}

.log-actions {
  display: flex;
  gap: 10px;
}

/* 自定义滚动条 */
.log-container::-webkit-scrollbar {
  width: 8px;
}

.log-container::-webkit-scrollbar-track {
  background: #2d2d2d;
}

.log-container::-webkit-scrollbar-thumb {
  background: #555;
  border-radius: 4px;
}

.log-container::-webkit-scrollbar-thumb:hover {
  background: #777;
}

@media (max-width: 768px) {
  .logs-header {
    flex-direction: column;
    align-items: stretch;
  }
  
  .logs-controls {
    justify-content: center;
  }
  
  .log-footer {
    flex-direction: column;
    gap: 10px;
    align-items: stretch;
  }
}
</style>